package concurrent.lock;

import org.junit.Test;

import java.util.concurrent.locks.LockSupport;

/**
 * @Author tuyou_cd
 * @Date 2020/8/17 10:21
 */
public class LockSupportTest {

    /**
     * 阻塞、唤醒简单测试
     */
    @Test
    public void parkUnparkTest() {

        final Thread main = Thread.currentThread();
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("唤醒主线程");
                LockSupport.unpark(main);
            }
        }.start();

        System.out.println("main阻塞");
        LockSupport.park();
        System.out.println("main被唤醒");
    }

    @Test
    public void blockerTest() {
        Object blocker = new Object();
        System.out.println(blocker);

        final Thread main = Thread.currentThread();
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("唤醒主线程");
                System.out.println(LockSupport.getBlocker(main));
                LockSupport.unpark(main);
            }
        }.start();

        System.out.println("main阻塞");
        LockSupport.park(blocker);
        System.out.println("main被唤醒");
    }
}
